package com.jfl.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jfl.annotation.Log;
import com.jfl.base.AbstractController;
import com.jfl.core.utils.ShiroUtils;
import com.jfl.enums.LogType;
import com.jfl.enums.Module;
import com.jfl.system.SysUserService;
import com.jfl.utils.AjaxUtil;

/**
 * 系统登录控制器
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月6日]
 * @since V1.00
 */
@Controller
public class SysLoginController extends AbstractController
{
    /**
     * dubbo接口 @Reference 通过配置文件连接服务
     */
    @Reference(version = "${jfl.version}")
    private SysUserService sysUserService;
    
    /**
     * 登录 POST
     * 
     * @param userName
     * @param password
     * @param rememberMe
     * @return
     */
    @Log(module = Module.USER, value = "用户登录", type = LogType.LOGIN)
    @PostMapping("login")
    @ResponseBody
    public ResponseEntity<ModelMap> login(String userName, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        // shiro登录
        subject.login(token);
        return setSuccessModelMap();
    }
    
    /**
     * 跳转登录页面
     * 
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (AjaxUtil.isAjaxRequest(request))
        {
            return AjaxUtil.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时，请重新登录！\"}");
        }
        
        return "login";
    }
    
    /**
     * 未授权
     * 
     * @return
     */
    @GetMapping("/unauth")
    public String unauth()
    {
        return "/error/unauth";
    }
    
    /**
     * 登出
     * 
     * @return
     */
    @GetMapping("/logout")
    public String logout()
    {
        // 登出
        ShiroUtils.logout();
        // 退出重定向到登录页面
        return "redirect:/login";
    }
}
